package com.demo.cms.webapp.interceptor;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.CookieInterceptor;

import com.demo.common.HtmlUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.util.ValueStack;


/**
 * 文章内容拦截器
 * 查找分页字段,对文章内容进行分页
 * 该拦截器配合CKEditor标准分页：
 *  <pre>
 * &lt;div page="true" style="page-break-after: always;"&gt;
 *	&lt;span style="display: none;"&gt;&nbsp;&lt;/span&gt;
 * &lt;/div&gt;
 * </pre>
 * @author ryuu.kk
 *
 */
public class ArticleContextInterceptor extends AbstractInterceptor {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = 5417381107421363591L;

	private static final Log LOG = LogFactory.getLog(ArticleContextInterceptor.class);

	/**
	 * 文章内容字段Key
	 */
	private String articleContent = "article.articleContent.content";
	
	/**
	 * 分隔符的属性标记
	 */
	private String attributeSign = "page";
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		if (LOG.isDebugEnabled()) {
			LOG.debug("enter ArticleContextInterceptor");
		}
		
		ActionContext ac = invocation.getInvocationContext();
		Map<String, Object> params = ac.getParameters();
		
		if (!params.containsKey(articleContent)) {
			//params.get(articleContent);
			return invocation.invoke();
		}
		
		String[] artHtmls = (String[]) params.get(articleContent);
		
		for (String artHtml : artHtmls) {
			//String[]
			List<String> pageHtml = HtmlUtils.htmlParse(artHtml, attributeSign);
			
			if (pageHtml != null && pageHtml.size() > 0) {
				params.remove(articleContent);
				for (int i = 0; i < pageHtml.size(); i++) {
					params.put("article.contentList[" + i + "].content", pageHtml.get(i));
				}
			}
		}
		return invocation.invoke();
	}


	public void setArticleContent(String articleName) {
		this.articleContent = articleName;
	}

	public void setAttributeSign(String attributeSign) {
		this.attributeSign = attributeSign;
	}

}
